import 'ol/ol.css';

import Map from "ol/Map";
import Feature from "ol/Feature";
import Point from "ol/geom/Point"
import Style from "ol/style/Style"
import Icon from "ol/style/Icon"
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";

import Select from "ol/interaction/Select";

import * as QinZhou from '@src/configs/GLOBAL_QinZhou.js';

console.log(QinZhou);

export const initialize = (id) => {

    const { CENTER, MAP_DEFAULT_ZOOM } = QinZhou;
    const map = new Map({ target: id });
    const renderer = map.getRenderer();

    map.setView(QinZhou.view);
    map.addLayer(QinZhou.layer);

    const qcSource = new VectorSource();
    const qcLayer = new VectorLayer();
    qcLayer.setSource(qcSource);
    map.addLayer(qcLayer);

    const ahtSource = new VectorSource();
    const ahtLayer = new VectorLayer();
    ahtLayer.setSource(ahtSource);
    map.addLayer(ahtLayer);

    const ycSource = new VectorSource();
    const ycLayer = new VectorLayer();
    ycLayer.setSource(ycSource);
    map.addLayer(ycLayer);

    let qcFeature = null;
    {
        qcFeature = new Feature();
        qcFeature.setId("QC001");
        const geometry = new Point(CENTER);
        const style = new Style({ zIndex: 0 });
        const icon = new Icon({ src: "/STS.png", anchor: [0.5, 0.5], rotation: 0.0, color: "#03a9f4" });
        style.setImage(icon);
        qcFeature.setGeometry(geometry);
        qcFeature.setStyle(style);
        qcSource.addFeature(qcFeature);
    }

    let ahtFeature = null;
    {
        ahtFeature = new Feature();
        ahtFeature.setId("V001");
        const geometry = new Point(CENTER);
        const style = new Style({ zIndex: 0 });
        const icon = new Icon({ src: "/aht.png", anchor: [0.5, 0.5], rotation: 0.0 });
        style.setImage(icon);
        ahtFeature.setGeometry(geometry);
        ahtFeature.setStyle(style);
        ahtSource.addFeature(ahtFeature);
    }

    let ycFeature = null;
    {
        ycFeature = new Feature();
        ycFeature.setId("YC001");
        const geometry = new Point(CENTER);
        const style = new Style({ zIndex: 0 });
        const icon = new Icon({ src: "/ARMG.png", anchor: [0.5, 0.5], rotation: 0.0 });
        style.setImage(icon);
        ycFeature.setGeometry(geometry);
        ycFeature.setStyle(style);
        ycSource.addFeature(ycFeature);
    }


    // 这个Select也是OpenLayers提供的API接口但是是注重交互的, 不像forEachFeatureAtPixel去做触发任务
    // const selectInteraction = new Select({
    //     layers: [qcLayer], // 指定要应用选择功能的图层
    //     style: () => {  // 自定义选中后的样式
    //         return [new Style({
    //             image: new Icon({ src: "/STS.png", anchor: [0.5, 0.5], rotation: 0.0, color: "#333333" }),
    //             zIndex: 0
    //         })];
    //     }
    // });
    // selectInteraction.on('select', function (e) {
    //     const selectedFeatures = e.selected; // 获取所有新选中的feature
    //     const deselectedFeatures = e.deselected; // 获取所有被取消选中的feature
    //     selectedFeatures.forEach(feature => console.log(feature.getProperties())); // 处理选中或取消选中的feature信息
    // });
    // map.addInteraction(selectInteraction); // 将选择交互添加到地图中

    // forEachFeatureAtPixel
    // 1. ol/Map 整理参数
    // 2. ol/renderer/Map 进一步整理参数, 遍历当前Map.state下所有Layers
    // 3. ol/renderer/Layer 抽象Layers包含forEachFeatureAtCoordinate函数
    // 4. ol/renderer/canvas/VectorLayer 继承抽象Layers的函数
    // 5. ol/renderer/canvas/ExecutorGroup
    // 6. ol/renderer/canvas/Executor
    //      Executor.executeHitDetection => Executor.execute_
    //      imageAnchor, imageWidth, imageHeight 循环4次做一个简单的包围盒判断

    let featurePointer = undefined; // 当前悬浮的
    let lastMoveinFeaturePointer = undefined; // 上一个悬浮的
    let lastSelectedFeaturePointer = undefined; // 上一个选择的
    let clickEvent = undefined;
  
    map.addEventListener("pointermove", (e) => {
        const { pixel, originalEvent } = e;
        const feature = map.forEachFeatureAtPixel(
            pixel,
            (feature, layer) => {
                // 如果这里不return, 那么穿透找到所有的feature
                // 否则只会找到最近一个添加的layer的一个feature (最靠近视口的)
                return feature;
            },
            {
                hitTolerance: 10, // 允许像素误差
                layerFilter: (layer) => {
                    // 过滤器
                    const baseClassName = Object.getPrototypeOf(layer).constructor.name;
                    if (baseClassName === "VectorLayer") {
                        return true;
                    }
                    return false;
                },
            },
        );
  
        featurePointer = feature;
  
        let moveInFlag = false;
        let moveOutFlag = false;
  
        if (featurePointer) {
            const featurePointerId = featurePointer.getId();
            if (lastMoveinFeaturePointer) {
                // 选了新的, 以前是旧的
                const lastMoveinFeaturePointerId = lastMoveinFeaturePointer.getId();
                if (lastMoveinFeaturePointerId !== featurePointerId) {
                    moveInFlag = true;
                    moveOutFlag = true;
                }
            } else if (lastMoveinFeaturePointer === undefined) {
                // 选了新的, 以前是空的
                moveInFlag = true;
            }
        } else if (featurePointer === undefined) {
            if (lastMoveinFeaturePointer) {
                // 选了空的, 以前是旧的
                const lastMoveinFeaturePointerId = lastMoveinFeaturePointer.getId();
                moveOutFlag = true;
            }
            // 选了空的, 以前就是空的
        }
  
        if (moveOutFlag) {
            const lastMoveinFeaturePointerId = lastMoveinFeaturePointer.getId();
            moveoutFeature(lastMoveinFeaturePointer);
            lastMoveinFeaturePointer = undefined;
        }
        if (moveInFlag) {
            const featurePointerId = featurePointer.getId();
            moveinFeature(featurePointer);
            lastMoveinFeaturePointer = featurePointer;
        }
    });
  
    map.addEventListener("click", () => {
        clearTimeout(clickEvent);
        clickEvent = setTimeout(singleClick, 200);
    });
  
    map.addEventListener("dblclick", (e) => {
        clearTimeout(clickEvent);
        doubleClick();
    });
  
    const singleClick = () => {
        // CancelSelect
        if (lastSelectedFeaturePointer) {
            const lastSelectedFeaturePointerId = lastSelectedFeaturePointer.getId();
            let cancelSelectedFlag = false;
            if (featurePointer) {
                const featurePointerId = featurePointer.getId();
                // 从旧的变成一个新的
                if (lastSelectedFeaturePointerId !== featurePointerId) {
                    cancelSelectedFlag = true;
                }
            }
            // 点空的
            else if (featurePointer === undefined) {
                cancelSelectedFlag = true;
            }
  
            if (cancelSelectedFlag) {
                cancelSelected(lastSelectedFeaturePointer);
                lastSelectedFeaturePointer = undefined;
            }
        }
  
        // Select
        if (featurePointer) {
            const featurePointerId = featurePointer.getId();
            lastSelectedFeaturePointer = featurePointer;
            selected(featurePointer);
        }
    };
  
    const doubleClick = () => {
        if (featurePointer) {
            const featurePointerId = featurePointer.getId();
            doubleClicked(featurePointer);
        }
    };
  
    const selected = (feature) => {
        console.log(`选择了${feature.getId()}`);
    };
    const cancelSelected = (feature) => {
        console.log(`取消选择了${feature.getId()}`);
    };
    const doubleClicked = (feature) => {
        console.log(`双击了${feature.getId()}`);
    };
    const moveinFeature = (feature) => {
        console.log(`移动入${feature.getId()}`);
    };
    const moveoutFeature = (feature) => {
        console.log(`移动出${feature.getId()}`);
    };
};